package cn.caplike.spring.security.user.details.service.service;

import cn.caplike.spring.security.user.details.service.domain.entity.MyUser;
import cn.caplike.spring.security.user.details.service.domain.entity.Role;
import cn.caplike.spring.security.user.details.service.mapper.AuthenticationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * UserDetailsService 的主要作用是: 获取数据库里面的信息，然后封装成对象
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-04-21 10:38
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private AuthenticationMapper authenticationMapper;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        // 根据用户名查询数据库，查到对应的用户
        MyUser myUser = authenticationMapper.loadUserByUsername(name);

        // ... 做一些异常处理，没有找到用户之类的
        if (myUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 根据用户ID，查询用户的角色
        List<Role> roles = authenticationMapper.findRoleByUserId(myUser.getId());
        // 添加角色
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        // 构建 Security 的 User 对象
        return new User(myUser.getName(), myUser.getPassword(), authorities);
    }

    @Autowired
    public void setAuthenticationMapper(AuthenticationMapper authenticationMapper) {
        this.authenticationMapper = authenticationMapper;
    }
}
